//
//  SiterAPI.m
//  sHome
//
//  Created by tracyhenry on 2022/8/15.
//  Copyright © 2022年 SiterWell. All rights reserved.
//

#import "SiterAPI.h"
#import "Netability.h"
#import "SiterUserNetManager.h"
#import "NSString+CY.h"
#import "NSData+wxAES.h"
#import "TimeHelper.h"
#import "Single.h"
#import "NVLogManager.h"
#import <AWSCore/AWSServiceEnum.h>
#import <CoreTelephony/CTCarrier.h>
#import <CoreTelephony/CTTelephonyNetworkInfo.h>

#define SiterConfig @"SiterConfig"
#define SiterUid @"SiterUid"
#define SiterAccessToken @"SiterAccessToken"
#define SiterrefreshToken @"SiterRefreshToken"
#define SiterIsTourist @"SiterIsTourist"
#define SiterTourilstName @"SiterTourilstName"
#define SiterDebug @"SiterDebug"
#define AESKey @"stiotvisitorcode"
@interface Siter()
    
@end

@implementation Siter(Authorization)
#pragma mark -method(用户信息数据读写)
-(NSString *)pid{
    return @"123456";
}

-(void)setUid:(NSNumber *)uid{
    NSUserDefaults *config = [NSUserDefaults standardUserDefaults];
    [config setValue:uid forKey:SiterUid];
    [config synchronize];
}

-(NSNumber *)uid{
    NSUserDefaults *config = [NSUserDefaults standardUserDefaults];
    NSNumber *responseObject = [config objectForKey:SiterUid];
    return responseObject;
}


-(void)setAccess_token:(NSString *)access_token{
    NSUserDefaults *config = [NSUserDefaults standardUserDefaults];
    [config setValue:access_token forKey:SiterAccessToken];
    [config synchronize];
}

-(NSString *)access_token{
    NSUserDefaults *config = [NSUserDefaults standardUserDefaults];
    NSString *responseObject = [config objectForKey:SiterAccessToken];
    return responseObject;
}

-(void)setRefresh_token:(NSString *)refresh_token{
    NSUserDefaults *config = [NSUserDefaults standardUserDefaults];
    [config setValue:refresh_token forKey:SiterrefreshToken];
    [config synchronize];
}

-(NSString *)refresh_token{
    NSUserDefaults *config = [NSUserDefaults standardUserDefaults];
    NSString *responseObject = [config objectForKey:SiterrefreshToken];
    return responseObject;
}

-(BOOL)isTourlist{
    NSUserDefaults *config = [NSUserDefaults standardUserDefaults];
    NSString *responseObject = [config objectForKey:SiterIsTourist];
    if([NSString isBlankString:responseObject]){
        return NO;
    }
    return YES;
}

-(void)setTourlist:(NSString *)tourlist{
    NSUserDefaults *config = [NSUserDefaults standardUserDefaults];
    [config setValue:tourlist forKey:SiterIsTourist];
    [config synchronize];
}

@end

@implementation Siter(Cloud)


-(AFHTTPSessionManager *)sessionWithDefaultAuthorization{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html", @"application/json", @"text/json", @"text/javascript", @"text/plain",nil];
    manager.requestSerializer.timeoutInterval = 10.f;
    AFJSONResponseSerializer *response = [AFJSONResponseSerializer serializer];
    response.removesKeysWithNullValues = YES;
    manager.responseSerializer = response;
    NSString *token = [self access_token];
    if(token == nil){
        token = @"";
    }
    [manager.requestSerializer setValue:[@"Bearer " stringByAppendingString:token] forHTTPHeaderField:@"Authorization"];
    [manager.requestSerializer setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    return manager;
}

-(AFHTTPSessionManager *)sessionWithDefaultAuthorizationJson{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html", @"application/json", @"text/json", @"text/javascript", @"text/plain", nil];
    manager.requestSerializer.timeoutInterval = 10.f;
    AFJSONResponseSerializer *response = [AFJSONResponseSerializer serializer];
    response.removesKeysWithNullValues = YES;
    manager.responseSerializer = response;
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    NSString *token = [self access_token];
    if(token == nil){
        token = @"";
    }
    [manager.requestSerializer setValue:[@"Bearer " stringByAppendingString:token] forHTTPHeaderField:@"Authorization"];
    return manager;
}


@end


@implementation Siter(User)
-(NSString *)getEnv{
    NSUserDefaults *config = [NSUserDefaults standardUserDefaults];
    NSString *siterProduct = [config objectForKey:SiterDebug];
    return [@"1" isEqualToString:siterProduct]?@"debug":@"release";
}


-(NSDictionary *)getConfig{
    NSUserDefaults *config = [NSUserDefaults standardUserDefaults];
    NSDictionary *config2 = [config objectForKey:SiterConfig];
    return config2;
}

-(void) setOnlineSite:(NSString* )domain{
    NSUserDefaults *config = [NSUserDefaults standardUserDefaults];
        [config setObject:domain forKey:@"siter_domain"];
        [config synchronize];
}

-(NSString *)getDomain{
   NSString *domain = [[NSUserDefaults standardUserDefaults] objectForKey:@"siter_domain"];
   return domain;
}


-(NSString *)getRegisterToken{
   NSString *domain = [[NSUserDefaults standardUserDefaults] objectForKey:@"register_token"];
   return domain;
}



-(NSString *)getSokectClientId{
   NSString *socketId = [[NSUserDefaults standardUserDefaults] objectForKey:@"siter_tourlist_username"];
    if([self isBlankString:socketId]){
        NSString *firstname = [self GUIDString];
        firstname = [firstname stringByReplacingOccurrencesOfString:@"-" withString:@""];
        [[NSUserDefaults standardUserDefaults] setObject:firstname forKey:@"siter_tourlist_username"];
        [[NSUserDefaults standardUserDefaults] synchronize];
        
        return firstname;
    }else{
        return socketId;
    }
   
}

-(NSString *)getTourlistName{
   NSString *siter_tourlist_username = [[NSUserDefaults standardUserDefaults] objectForKey:SiterTourilstName];
    if([self isBlankString:siter_tourlist_username]){
        NSString *firstname = [self GUIDString];
        firstname = [@"st" stringByAppendingString:[[self GUIDString] stringByReplacingOccurrencesOfString:@"-" withString:@""]];
        [[NSUserDefaults standardUserDefaults] setObject:firstname forKey:SiterTourilstName];
        [[NSUserDefaults standardUserDefaults] synchronize];
        
        return firstname;
    }else{
        return siter_tourlist_username;
    }
   
}

//登录
-(void) userLogin:(NSString*)userName withPwd:(NSString *)pwd callback:(void(^)(id user,NSError*,NSError*)) block{
        NSDictionary *param = @{
             @"username" : userName,
             @"password" : pwd
             };

        NSString *host = [self getDomain];
         
    
         [[self sessionWithDefaultAuthorization] POST:[NSString stringWithFormat:@"%@/sso/login",host] parameters:param headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
             NSNumber *codee = responseObject[@"code"];
             int code = [codee intValue];
             if(code==200){
                 [self setTourlist:@""];
                 [self setUid:responseObject[@"data"][@"id"]];
                 [self setAccess_token:responseObject[@"data"][@"token"]];
                 [self setRefresh_token:responseObject[@"data"][@"refreshToken"]];

                 !block ?: block(responseObject, nil,nil);
             }else{
                 NSError *error = [[NSError alloc] initWithDomain:NSCocoaErrorDomain code:code userInfo:nil];
                 !block ?: block(nil, error,nil);
             }

             } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                 !block ?: block(nil,nil, error);
             }];
    
}

//游客注册
-(void) tourlistRegister:(void(^)(id user,NSError*,NSError*)) block{
    
    
    NSString *timer = [@"siter" stringByAppendingString:[TimeHelper getCurrentTimesByDay]];
    
    NSString *data = [NSData aes256_encrypt:AESKey Encrypttext:timer];

        NSDictionary *param = @{
             @"visitorId" :data
             };
       
        NSString *host = [self getDomain];
         [[self sessionWithDefaultAuthorization] POST:[NSString stringWithFormat:@"%@/sso/obtainVisitorId",host] parameters:param headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
             NSNumber *codee = responseObject[@"code"];
             int code = [codee intValue];
             if(code==200){
                 NSString *username = responseObject[@"data"];
                 [self tourlistLogin:username withBlock:block];
             }else{
                 NSError *error = [[NSError alloc] initWithDomain:NSCocoaErrorDomain code:code userInfo:nil];
                 !block ?: block(nil, error,nil);
             }

             } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                 !block ?: block(nil,nil, error);
             }];
    
}

//游客登录
-(void) tourlistLogin:(NSString *)username withBlock:(void(^)(id user,NSError*,NSError*)) block{
        NSDictionary *param = @{
             @"visitorId" : username
             };
        NSString *host = [self getDomain];
         [[self sessionWithDefaultAuthorization] POST:[NSString stringWithFormat:@"%@/sso/loginVisitor",host] parameters:param headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
             NSNumber *codee = responseObject[@"code"];
             int code = [codee intValue];
             if(code==200){
                 [self setTourlist:@"1"];
                 [self setUid:responseObject[@"data"][@"id"]];
                 [self setAccess_token:responseObject[@"data"][@"token"]];
                 [self setRefresh_token:responseObject[@"data"][@"refreshToken"]];
                 [[NSNotificationCenter defaultCenter] postNotificationName:NotificationUserLoggedIn object:nil userInfo:nil];
                 !block ?: block(responseObject, nil,nil);
             }else{
                 NSError *error = [[NSError alloc] initWithDomain:NSCocoaErrorDomain code:code userInfo:nil];
                 !block ?: block(nil, error,nil);
             }

             } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                 !block ?: block(nil,nil, error);
             }];
    
}

//google登录
-(void) userGoogleLogin:(NSString*)idToken callback:(void(^)(id user,NSError*,NSError*)) block{
    NSDictionary *param = @{@"thirdToken" : idToken,@"clentId":@"565563998542-thaj369altkbu6dvj0m1r3u6m2mm5qk3.apps.googleusercontent.com"};
        NSString *host = [self getDomain];
    
         [[self sessionWithDefaultAuthorizationJson] POST:[NSString stringWithFormat:@"%@/sso/loginGoogle",host] parameters:param headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
             NSNumber *codee = responseObject[@"code"];
             int code = [codee intValue];
             if(code==200){
                 [self setTourlist:@""];
                 [self setUid:responseObject[@"data"][@"id"]];
                 [self setAccess_token:responseObject[@"data"][@"token"]];
                 [self setRefresh_token:responseObject[@"data"][@"refreshToken"]];

                 !block ?: block(responseObject, nil,nil);
             }else{
                 NSError *error = [[NSError alloc] initWithDomain:NSCocoaErrorDomain code:code userInfo:nil];
                 !block ?: block(nil, error,nil);
             }

             } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                 !block ?: block(nil,nil, error);
             }];
    
}

-(void)refreshTokenwithCallback:(void(^)(id user,NSError*)) block{
    NSUserDefaults *config = [NSUserDefaults standardUserDefaults];
    NSString *refreshToken = [config objectForKey:SiterrefreshToken];
    NVLogInfo(@"刷新了refresh_token:%@",refreshToken);
    NSDictionary *param = @{
        @"refresh_token" : refreshToken==nil?@"":refreshToken,
         @"client_id": @"portal-app",
         @"grant_type": @"refresh_token",
         @"client_secret": @"123456",
         };
    
    NSString *refreshtoken_base_url =  [self getConfig][[self getEnv]][@"base_url"];
    NSString *refreshtoken_url = [refreshtoken_base_url stringByAppendingString:@"iot-auth/oauth/token"];
    
    [[self sessionWithDefaultAuthorization] POST:refreshtoken_url parameters:param headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self setAccess_token:responseObject[@"access_token"]];
        [self setRefresh_token:responseObject[@"refresh_token"]];
        !block ?: block(responseObject, nil);
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            //错误http码示例，待优化
            //            NSString* errResponse = [[NSString alloc] initWithData:(NSData *)error.userInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] encoding:NSUTF8StringEncoding];
            NSHTTPURLResponse * responses = (NSHTTPURLResponse *)task.response;   //或者task.response
            NSInteger errcode = responses.statusCode;
            NSError *error2 = [[NSError alloc] initWithDomain:NSCocoaErrorDomain code:errcode userInfo:nil];
            !block ?: block(nil, error2);
        }];
}


-(void) logout{
    [self setTourlist:@""];
    [self setUid:nil];
    [self setAccess_token:nil];
    [self setRefresh_token:nil];
}

-(BOOL) isBlankString:(NSString *)string {
    
    if (string == nil || string == NULL) {
        
        return YES;
        
    }
    if ([string isKindOfClass:[NSNull class]]) {
        
        return YES;
        
    }
    
    if ([[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length]==0) {
        
        return YES;
        
    }
    if ([string isEqualToString:@"(null)"]) {
        
        return YES;
        
    }
    
    return NO;
    
}

- (NSString*)GUIDString {
    CFUUIDRef newUniqueID = CFUUIDCreate(kCFAllocatorDefault);
    CFStringRef newUniqueIDString = CFUUIDCreateString(kCFAllocatorDefault, newUniqueID);
    NSString *guid = (__bridge NSString *)newUniqueIDString;
    CFRelease(newUniqueIDString);
    CFRelease(newUniqueID);
    return([guid lowercaseString]);
}


@end


@implementation Siter(Config)
-(NSString *)getEnv{
    NSUserDefaults *config = [NSUserDefaults standardUserDefaults];
    NSString *siterProduct = [config objectForKey:SiterDebug];
    return [@"1" isEqualToString:siterProduct]?@"debug":([@"2" isEqualToString:siterProduct]?@"debug2":@"release");
}


-(NSDictionary *)getConfig{
    NSUserDefaults *config = [NSUserDefaults standardUserDefaults];
    NSDictionary *config2 = [config objectForKey:SiterConfig];
    return config2;
}

-(void) config:(NSDictionary*) config{
    
   config = @{
        @"release":@{
            @"base_url":@"https://siterwellcloud.com/",
            @"iot_endport":@"https://a22kpq659tmps7-ats.iot.us-east-1.amazonaws.com",
            @"identify_pool_id":@"us-east-1:251c7532-6323-4efe-ac8f-7d47d2b85496",
            @"region":@(AWSRegionUSEast1),
            @"googlehome_project_id":@"familylinkpro-14733",
            @"alexa_redict_url":@"https://siterwellcloud.com",
            @"alexa_skill_id":@"amzn1.ask.skill.8e321d63-3aac-4aeb-971f-b6223d4c9be0",
            @"alexa_client_id":@"amzn1.application-oa2-client.9e41af8afe584898ae6a328c80516695"
        },
        @"debug":@{
            
            //  #define IOT_ENDPOINT @"https://a22kpq659tmps7-ats.iot.ap-southeast-1.amazonaws.com"
            //  #define IDENTITY_POOL_ID @"ap-southeast-1:b135ff68-0915-4591-b3d0-7202fb027491"
            //  #define REGION AWSRegionAPSoutheast1

            @"base_url":@"http://44.226.239.77:8201/",
            @"iot_endport":@"https://a22kpq659tmps7-ats.iot.us-west-2.amazonaws.com",
            @"identify_pool_id":@"us-west-2:11f3d596-ede2-4673-b59c-618c10faaa50",
            @"region":@(AWSRegionUSWest2),
            @"googlehome_project_id":@"boys-31146",
            @"alexa_redict_url":@"https://st-iot.net",
            @"alexa_skill_id":@"amzn1.ask.skill.4e29c27d-ea75-4d16-8f35-1104101bb6a7",
            @"alexa_client_id":@"amzn1.application-oa2-client.a3902050cd0e472eaa0e3584626a6f0d"
        },
        @"debug2":@{
            @"base_url":@"https://st-iot.net/iot-test/",
            @"iot_endport":@"https://a22kpq659tmps7-ats.iot.ap-southeast-1.amazonaws.com",
            @"identify_pool_id":@"ap-southeast-1:b135ff68-0915-4591-b3d0-7202fb027491",
            @"region":@(AWSRegionAPSoutheast1),
            @"googlehome_project_id":@"boys-31146",
            @"alexa_redict_url":@"https://st-iot.net",
            @"alexa_skill_id":@"amzn1.ask.skill.4e29c27d-ea75-4d16-8f35-1104101bb6a7",
            @"alexa_client_id":@"amzn1.application-oa2-client.a3902050cd0e472eaa0e3584626a6f0d"
        },
    };
    
    NSUserDefaults *config2 = [NSUserDefaults standardUserDefaults];
    [config2 setValue:config forKey:SiterConfig];
    [config2 synchronize];

    [self setOnlineSite:[[self getConfig][[self getEnv]][@"base_url"] stringByAppendingString:@"iot-portal"]];
}

-(NSString *)getIOTENDPOINT{
    return [self getConfig][[self getEnv]][@"iot_endport"];

}

-(NSString *)getIDENTITYPOOLID{
    return [self getConfig][[self getEnv]][@"identify_pool_id"];
}

-(AWSRegionType)getREGION{
    return [[self getConfig][[self getEnv]][@"region"] intValue];
}


-(NSString *)getAWSIOTDATAMANAGERKEY{
    return @"MyIotDataManager";
}


-(NSString *)setIsProductSwitch{
    
    NSUserDefaults *config = [NSUserDefaults standardUserDefaults];
    NSString *siterProduct = [config objectForKey:SiterDebug];
    
    NSString *re = [@"1" isEqualToString:siterProduct]?nil:@"1";
    [config setValue:re forKey:SiterDebug];
    [config synchronize];
    return re;
}


-(void)setProductSwitch:(EnvStatus)value{
    
    NSUserDefaults *config = [NSUserDefaults standardUserDefaults];
    NSString *de = nil;
    if(value==EnvStatus_debug2){
        de = @"2";
    }else if(value==EnvStatus_debug){
        de = @"1";
    }
    [config setValue:de forKey:SiterDebug];
    [config synchronize];
}


-(NSString *)getPrivacyURL{
    NSArray *appLanguages = [[NSUserDefaults standardUserDefaults] objectForKey:@"AppleLanguages"];
     NSString *languageName = [appLanguages objectAtIndex:0];
    NSString * url = [languageName containsString:@"zh"]?@"readme_privacy_policy_zh.html":@"readme_privacy_policy_en.html";
    return [NSString stringWithFormat:@"%@%@",([self getConfig][[self getEnv]][@"base_url"]),url];
}

-(NSString *)getUserAgreementURL{
    NSArray *appLanguages = [[NSUserDefaults standardUserDefaults] objectForKey:@"AppleLanguages"];
     NSString *languageName = [appLanguages objectAtIndex:0];
    NSString * url = [languageName containsString:@"zh"]?@"readme_user_agreement_zh.html":@"readme_user_agreement_en.html";
    return [NSString stringWithFormat:@"%@%@",([self getConfig][[self getEnv]][@"base_url"]),url];
}

@end


@implementation Siter(AlexaAndGoogleHome)

-(NSString *)getStateCodeURL{
    NSString *code = [[self GUIDString] stringByReplacingOccurrencesOfString:@"-" withString:@""];
    NSString *alexa_redict_url = [self getConfig][[self getEnv]][@"alexa_redict_url"];
    NSString *alexa_client_id = [self getConfig][[self getEnv]][@"alexa_client_id"];
    NSString *de = [NSString stringWithFormat:@"https://www.amazon.com/ap/oa?client_id=%@&scope=alexa::skills:account_linking&response_type=code&redirect_uri=%@&state=%@",alexa_client_id,alexa_redict_url,code];

    return de;
}

-(NSString *)getStateCodeURLByApp{
    NSString *code = [[self GUIDString] stringByReplacingOccurrencesOfString:@"-" withString:@""];
    NSString *alexa_redict_url = [self getConfig][[self getEnv]][@"alexa_redict_url"];
    NSString *alexa_client_id = [self getConfig][[self getEnv]][@"alexa_client_id"];
    NSString *stage = [@"release" isEqualToString:[self getEnv]]?@"live":@"development";
    NSString *de = [NSString stringWithFormat:@"https://alexa.amazon.com/spa/skill-account-linking-consent?fragment=skill-account-linking-consent&client_id=%@&scope=alexa::skills:account_linking&skill_stage=%@&response_type=code&redirect_uri=%@&state=%@",alexa_client_id,stage,alexa_redict_url,code];

    return de;
}

-(NSString *)getRedirectURL{
    return [self getConfig][[self getEnv]][@"alexa_redict_url"];
}

-(NSString *)getAlexaSkillId{
    return [self getConfig][[self getEnv]][@"alexa_skill_id"];
}

-(NSString *)getGoogleAssistantId{
    return [self getConfig][[self getEnv]][@"googlehome_project_id"];
}
@end
